package servlet;

import com.octo.captcha.service.CaptchaServiceException;
import entity.Book;
import entity.BookService;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import util.CaptchaServiceSingleton;
import util.Utilities;

/**
 *
 * @author Francis
 */
public class AddBookServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //todo: read the infomration from the jsp
        String bookName = request.getParameter("bookname");
        String category = request.getParameter("category2").trim();
        String description = request.getParameter("itemDescription");
        String price = request.getParameter("price").trim();
        String quantity = request.getParameter("quantity").trim();        
        String tags = request.getParameter("tags").trim();
        String tag1 = null;
        String tag2 = null;
        String tag3 = null;
        String tag4 = null;
        String tag5 = null;
        String condition = request.getParameter("itemCondition").trim();
        boolean meet;
        String location;
        if(request.getParameter("meet") == null){
            meet=false;
            location="";
        }else{
            meet = true;
            location = request.getParameter("tradeLocation");
        }
        boolean mail1;
        String postalFee1="";
        if(request.getParameter("mail1") == null){
            mail1=false;
        }else{
            mail1 = true;
            postalFee1 = request.getParameter("postalFee1");
        }
        boolean mail2;
        String postalFee2="";
        if(request.getParameter("mail2") == null){
            mail2=false;
        }else{
            mail2 = true;
            postalFee2 = request.getParameter("postalFee2");
        }
        boolean other_trading_method;
        String other_trading_method_detail;
        if(request.getParameter("other_trading_method") == null){
            other_trading_method=false;
            other_trading_method_detail="";
        }else{
            other_trading_method = true;
            other_trading_method_detail = request.getParameter("other_trading_method_detail");
        }
        boolean cash = request.getParameter("cash") == null ? false : true;
        boolean ebank = request.getParameter("ebank") == null ? false : true;
        boolean credit = request.getParameter("credit") == null ? false : true;
        boolean cheque = request.getParameter("cheque") == null ? false : true;
        boolean paypal = request.getParameter("paypal") == null ? false : true;
        boolean other_paying_method;
        String other_paying_method_detail;
        if(request.getParameter("other_paying_method") == null){
            other_paying_method=false;
            other_paying_method_detail="";
        }else{
            other_paying_method = true;
            other_paying_method_detail = request.getParameter("other_paying_method_detail");
        }


        String minRating = request.getParameter("minRating").trim();
        String activePeriod = request.getParameter("activePeriod").trim();
        String captchaCode = request.getParameter("bookcaptchacode");



        // Temporarily store the data that user input to the form
        // todo: actually it is not temporarily.... these values have to be deleted form the session manually
        HttpSession session = request.getSession(true);
        session.setAttribute("category", category);
        session.setAttribute("bookName", bookName);
        session.setAttribute("itemDescription", description);
        session.setAttribute("price", price);
        session.setAttribute("activePeriod",activePeriod);
        session.setAttribute("quantity", quantity);        
        session.setAttribute("tags", tags);
        session.setAttribute("condition", condition);
        session.setAttribute("minRating", minRating);
        session.setAttribute("meet",meet);
        session.setAttribute("location", location);
        session.setAttribute("mail1",mail1);
        session.setAttribute("postalFee1",postalFee1);
        session.setAttribute("mail2",mail2);
        session.setAttribute("postalFee2",postalFee2);
        session.setAttribute("other_trading_method",other_trading_method);
        session.setAttribute("other_trading_method_detail",other_trading_method_detail);
        session.setAttribute("cash",cash);
        session.setAttribute("ebank",ebank);
        session.setAttribute("credit",credit);
        session.setAttribute("cheque",cheque);
        session.setAttribute("paypal",paypal);
        session.setAttribute("other_paying_method",other_paying_method);
        session.setAttribute("other_paying_method_detail",other_paying_method_detail);

        //convert to UTF-8 for internal processing
        bookName = Utilities.toUTF8(bookName);
        description = Utilities.toUTF8(description);
        location = Utilities.toUTF8(location);
        tags = Utilities.toUTF8(tags);
        other_trading_method_detail = Utilities.toUTF8(other_trading_method_detail);
        other_paying_method_detail = Utilities.toUTF8(other_paying_method_detail);

        //todo: use personID instead, if possible
        //String personID = (String) session.getAttribute("personID");
        //int personID = 1;

        //check the necessary fields FIRST
        if (bookName.isEmpty() || price.isEmpty() || quantity.isEmpty() || tags.isEmpty() || condition.isEmpty() || minRating.isEmpty() || "-99999".equals(category)) {
            response.sendRedirect("AddItem.jsp?msg=necessary_empty_error");
            return;
        }

        // Check for valid Captcha code entered by user
        //HttpSession session = request.getSession(true);
        try {
            boolean isCorrectCaptcha = false;
            isCorrectCaptcha = CaptchaServiceSingleton.getInstance().validateResponseForID(session.getId(), captchaCode);
            if (!isCorrectCaptcha) {
                response.sendRedirect("AddItem.jsp?msg=cap_error");
                return;
            }
        } catch (CaptchaServiceException e) {
            //should not happen, may be thrown if the id is not valid
        }

        //******************** tag1, tag2, tag3 *********         t
        String[] tagTokens = tags.split(",");
        if (tagTokens.length > 0) {
            tag1 = tagTokens[0].trim();
        }
        if (tagTokens.length > 1) {
            tag2 = tagTokens[1].trim();
        }
        if (tagTokens.length > 2) {
            tag3 = tagTokens[2].trim();
        }
        if (tagTokens.length > 3) {
            tag4 = tagTokens[3].trim();
        }
        if (tagTokens.length > 4) {
            tag5 = tagTokens[4].trim();
        }
        //todo: 2 more tags....

        //********************* Price *********************
        double priceDouble = 0;
        try {
            priceDouble = NumberFormat.getCurrencyInstance(Locale.US).parse("$" + price).doubleValue();
        } catch (Exception e) {
            response.sendRedirect("AddItem.jsp?msg=money_error");
            return;
        }

        //********************* Quantity ******************
        int quantityInt = 0;
        try {
            quantityInt = Integer.parseInt(quantity);
        } catch (Exception e) {
            response.sendRedirect("AddItem.jsp?msg=quantity_error");
            return;
        }
        if (quantityInt <= 0) {
            response.sendRedirect("AddItem.jsp?msg=quantity_error");
            return;
        }
        //********************* Condition ****************
        int conditionInt = 0;
        //if(!condition.isEmpty()){  //not optional field
        try {
            conditionInt = Integer.parseInt(condition);
        } catch (Exception e) {
            response.sendRedirect("AddItem.jsp?msg=condition_error");
            return;
        }
        if (conditionInt < 0) {
            response.sendRedirect("AddItem.jsp?msg=condition_error");
        }
        //}
        //********************* Min Rating ****************
        int minRatingInt = 0;
        try {
            minRatingInt = Integer.parseInt(minRating);
        } catch (Exception e) {
            response.sendRedirect("AddItem.jsp?msg=minRating_error");
            return;
        }
        //****************** Expiry Day ****************
        int activePeriodInt = 0;

        try {
            activePeriodInt = Integer.parseInt(activePeriod);
        } catch (Exception e) {
            response.sendRedirect("AddItem.jsp?msg=activePeriod_error");
            return;
        }
        if (activePeriodInt < 0) {
            response.sendRedirect("AddItem.jsp?msg=activePeriod_error");
        }

        //********************* Category   ****************
        int categoryInt = 0;
        try {
            categoryInt = Integer.parseInt(category);
        } catch (Exception e) {
            response.sendRedirect("AddItem.jsp?msg=category_error");
            return;
        }
        
        double postalFee1Double = 0;
        if(postalFee1.equals("")){
            postalFee1="0";
        }
        try {
            postalFee1Double = NumberFormat.getCurrencyInstance(Locale.US).parse("$" + postalFee1).doubleValue();
        } catch (Exception e) {
            response.sendRedirect("AddItem.jsp?msg=postalFee_error");
            return;
        }
        double postalFee2Double = 0;
        if(postalFee2.equals("")){
            postalFee2="0";
        }
        try {
            postalFee2Double = NumberFormat.getCurrencyInstance(Locale.US).parse("$" + postalFee2).doubleValue();
        } catch (Exception e) {
            response.sendRedirect("AddItem.jsp?msg=postalFee_error");
            return;
        }
        
        //get the image path
        String image1 = (String) session.getAttribute("image1");
        String image2 = (String) session.getAttribute("image2");
        String image3 = (String) session.getAttribute("image3");

        if (image3 != null && image2 == null) {
            image2 = image3;
            image3 = null;
        }
        if (image2 != null && image1 == null) {
            image1 = image2;
            image2 = null;
        }
        /*
        if(image1 == null) {
            image1 = "/default/no_photo.jpg";
        }*/

        //last step get the peronID and check if the login expired.
        Integer personID = (Integer) session.getAttribute("personID");
        if (personID == null) {
            //login expired
            response.sendRedirect("LoginExpired.jsp");
            return;
        }

        //create a DB entity
        Book book = new Book();

        book.setDescription(description);
        //book.setCategory(0);//todo:category id
        book.setCategory(categoryInt);
        book.setLocation(location);
        book.setName(bookName);
        book.setPrice(new BigDecimal(priceDouble));
        book.setQuantity(quantityInt);
        book.setStatusCode(0);
        book.setAddDate(Utilities.now());
        book.setCondition(conditionInt);
        book.setTag1(tag1);
        book.setTag2(tag2);
        book.setTag3(tag3);
        book.setTag4(tag4);
        book.setTag5(tag5);
        book.setMinRating(minRatingInt);
        book.setActivePeriod(activePeriodInt);
        book.setEndDate(Utilities.nowIncrementDay(activePeriodInt));


        book.setImage1(image1);
        book.setImage2(image2);
        book.setImage3(image3);

        book.setClicks(0);
        book.setPersonID(personID);
        book.setIsAdvItem(false);
        book.setIsBuyNowItem(true);
        book.setIsGroupBuyItem(false);
        book.setAddIP(request.getRemoteAddr());
        book.setMeet(meet);
        book.setMail1(mail1);
        book.setMail2(mail2);
        book.setPostalFee1(new BigDecimal(postalFee1Double));
        book.setPostalFee2(new BigDecimal(postalFee2Double));
        book.setOtherTradingMethod(other_trading_method);
        book.setOtherTradingMethodDetail(other_trading_method_detail);
        book.setCash(cash);
        book.setEbank(ebank);
        book.setCredit(credit);
        book.setCheque(cheque);
        book.setPaypal(paypal);
        book.setOtherPayingMethod(other_paying_method);
        book.setOtherPayingMethodDetail(other_paying_method_detail);
        //todo:set number of time of renew        

        //store into the db
        boolean result = BookService.persist(book);
        response.getWriter().println(result);

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
